package cn.hdmis.security.action;

import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;
import org.apache.commons.lang.StringUtils;
import org.hibernate.dialect.IngresDialect;
import org.springframework.transaction.annotation.Transactional;

import net.sf.json.JSONArray;
import net.sf.json.JsonConfig;
import net.sf.json.util.CycleDetectionStrategy;
import cn.hdmis.action.BaseAction;
import cn.hdmis.security.entity.Resources;
import cn.hdmis.security.entity.Role;
import cn.hdmis.security.entity.User;
import cn.hdmis.security.service.ResourcesService;
import cn.hdmis.security.service.RoleService;
import cn.hdmis.security.service.UserService;
import cn.hdmis.util.SysMessageBean;

public class SecurityAction extends BaseAction{
	
	private static final long serialVersionUID = 2140131656108306488L;
	@Resource
	private ResourcesService resourcesService;
	@Resource
	private RoleService roleService;
	@Resource
	private UserService userService;
	private Role role;
	private Resources res;
	private User user;
	/**
	 * getResourcesJson()
	 * TODO 权限资源管理tree json数据
	 * @Exception 异常对象
	 * @since  CodingExample　Ver(编码范例查看) 1.1
	*/
	public void getResourcesJson(){
		try {
			List<Resources> list  = new ArrayList<Resources>();
			list =  resourcesService.getRootList();//获取树顶点
			JsonConfig jsonConfig = new JsonConfig(); //建立配置文件
			jsonConfig.setIgnoreDefaultExcludes(false); //设置默认忽略
			jsonConfig.setAllowNonStringKeys(false);
			jsonConfig.setExcludes(new String[]{"system"});  //只要将所需忽略字段加到数组中即可，在上述案例中，所要忽略的是“libs”，那么将其添到数组中即可，在实际测试中，我发现在所返回数组中，存在大量无用属性，如“multipartRequestHandler”，“servletWrapper”，那么也可以将这两个加到忽略数组中.
			jsonConfig.setCycleDetectionStrategy(CycleDetectionStrategy.LENIENT);   //不过经过测试，第2种方法有些悲剧，虽然可以使用，但其结果貌似循环数次，至于为啥，还请高人指点。
			JSONArray json = JSONArray.fromObject(list,jsonConfig); //加载配置文件
			String jsonString =  json.toString().replace("\"name\"", "\"text\"");
			responseJson(jsonString);
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("find resource from database error:"+e.getMessage());
		}
		
	}
	
	/**
	 * addResources()
	 * TODO (将resource对象插入数据库)
	 * @Exception 异常对象
	 * @since  CodingExample　Ver(编码范例查看) 1.1
	*/
	public void addResources(){
		try {
			resourcesService.save(res);
			responseJson("数据已成功保存！");
		} catch (Exception e) {
			e.printStackTrace();
			responseJson(e.getMessage());
			logger.error("insert resource to database error:"+e.getMessage());
		}
	}
	public String iniEditRes(){
		try {
			String id = this.getRequest().getParameter("id");
			if(StringUtils.isNotBlank(id)){
				res = resourcesService.findByID(Integer.valueOf(id));
				return "editRes";
			}
		} catch (Exception e) {
			e.printStackTrace();
			responseJson(new SysMessageBean("error","资源信息更初始化出错！").toJson());
		}
		return null;
	}
	/**
	 * editRes(更新权限资源信息)
	 * TODO(这里描述这个方法适用条件 – 可选)
	 * @Exception 异常对象
	 * @since  CodingExample　Ver(编码范例查看) 1.1
	*/
	public void editRes(){
		try {
			resourcesService.saveOrUpdate(res);
			responseJson(new SysMessageBean("info","资源信息已更新!").toJson());
		} catch (Exception e) {
			e.printStackTrace();
			responseJson(new SysMessageBean("error","资源信息更新出错!").toJson());
		}
	}
	/**
	 * deleRes(删除资源)
	 * @return String    DOM对象
	 * @Exception 异常对象
	 * @since  CodingExample　Ver(编码范例查看) 1.1
	*/
	public void deleteRes(){
		try {
			String id = this.getRequest().getParameter("id");
			if(StringUtils.isBlank(id)) throw new NullPointerException("Resources id is null");
			//Resources rs = resourcesService.findByID(Integer.valueOf(id));
			resourcesService.delete(Integer.valueOf(id));
			responseJson("权限资源ID:"+id+"已成功删除！");
		} catch (Exception e) {
			e.printStackTrace();
			responseJson(e.getMessage());
			logger.error("delete resource from database error:"+e.getMessage());
		}
	}
	
	public void getRoleJson(){
		try {
			List<Role> list =  roleService.findAllEntity();//获取树顶点
			JSONArray json = JSONArray.fromObject(list); //加载配置文件
			String jsonString =  json.toString().replace("\"name\"", "\"text\"");
			responseJson(jsonString);
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("find role list from database error:"+e.getMessage());
		}
		
	}
	/**
	 * addRole(新增角色)
	 * @Exception 异常对象
	 * @since  CodingExample　Ver(编码范例查看) 1.1
	*/
	public void addRole(){
		try {
			roleService.save(role);
			responseJson("数据已成功保存！");
		} catch (Exception e) {
			e.printStackTrace();
			responseJson(e.getMessage());
			logger.error("add Role to database error:"+e.getMessage());
		}
	}
	
	/**
	 * iniEditRole(初始化角色)
	 * TODO(这里描述这个方法适用条件 – 可选)
	 * @return String    DOM对象
	 * @Exception 异常对象
	 * @since  CodingExample　Ver(编码范例查看) 1.1
	*/
	public String iniEditRole(){
		try {
			String id = this.getRequest().getParameter("id");
			if(StringUtils.isNotBlank(id)){
				role = roleService.findByID(Integer.valueOf(id));
				return "editRole";
			}
		} catch (Exception e) {
			e.printStackTrace();
			responseJson(new SysMessageBean("error","资源信息更初始化出错！").toJson());
		}
		return null;
	}
	/**
	 * editRole(更新角色信息)
	 * TODO(这里描述这个方法适用条件 – 可选)
	 * @Exception 异常对象
	 * @since  CodingExample　Ver(编码范例查看) 1.1
	*/
	public void editRole(){
		try {
			roleService.saveOrUpdate(role);
			responseJson(new SysMessageBean("info","角色信息已更新!").toJson());
		} catch (Exception e) {
			e.printStackTrace();
			responseJson(new SysMessageBean("error","角色信息更新出错!").toJson());
		}
	}
	/**
	 * deleRole(删除角色)
	 * TODO(这里描述这个方法适用条件 – 可选)
	 * @return String    DOM对象
	 * @Exception 异常对象
	 * @since  CodingExample　Ver(编码范例查看) 1.1
	*/
	public void deleteRole(){
		try {
			String id = this.getRequest().getParameter("id");
			if(StringUtils.isBlank(id)) throw new NullPointerException("role id is null");
			//Resources rs = resourcesService.findByID(Integer.valueOf(id));
			roleService.delete(Integer.valueOf(id));
			responseJson("角色ID:"+id+"已成功删除！");
		} catch (Exception e) {
			e.printStackTrace();
			responseJson(e.getMessage());
			logger.error("delete role from database error:"+e.getMessage());
		}
	}
	public void getUserListJoson(){
		List<User> list = userService.findAllEntity();//获取树顶点
		JSONArray json = JSONArray.fromObject(list); //加载配置文件
		responseJson(json.toString());
	}
	public void addUser(){
		userService.saveOrUpdate(user);
		responseJson("当前操作已成功！");
	}
	public String iniUser(){
		try {
			String id = this.getRequest().getParameter("id");
			if(StringUtils.isNotBlank(id)){
				user = userService.findByID(Integer.valueOf(id));
				return "editUser";
			}
		} catch (Exception e) {
			e.printStackTrace();
			responseJson(new SysMessageBean("error","初始化用户出错！").toJson());
		}
		return null;
	}
	public void setRes(Resources res) {
		this.res = res;
	}

	public Resources getRes() {
		return res;
	}

	public void setRole(Role role) {
		this.role = role;
	}

	public Role getRole() {
		return role;
	}

	public User getUser() {
		return user;
	}

	public void setUser(User user) {
		this.user = user;
	}


}
